    //
//  TopicViewController.m
//  AgriMobile
//
//  Created by 春名 啓作 on 11/05/14.
//  Copyright 2011 （株）アグリコミュニケーションズ. All rights reserved.
//

#import "TopicViewController.h"
#define BTN_TOPIC 1
#define BTN_COMMENT 2

#define C_title		0
#define C_url		1
#define C_author	2
#define C_date		3
#define C_body		4
#define C_images	5

@implementation TopicViewController
@synthesize topicId;
@synthesize parentId;

NSArray *topicData = nil;
int btnTarget = 0;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement loadView to create a view hierarchy programmatically, without using a nib.
/*
- (void)loadView {

}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	NSLog(@"TopicViewController - viewDidLoad");
	
	NSString* btnTitle = @"コメント";
	if ([topicId rangeOfString:@"page_fh_album&"].location != NSNotFound) {
		btnTitle = @"写真を追加";
	}

	if ([topicId rangeOfString:@"a=page_h_message"].location == NSNotFound) {
		UIBarButtonItem *btn = [[[UIBarButtonItem alloc]
							 initWithTitle:btnTitle
							 style:UIBarButtonItemStyleBordered
							 target:self
							 action:@selector(clickButton:)] retain];
		self.navigationItem.rightBarButtonItem = btn;
		[btn release];
	}
}

/*
- (void)viewDidAppear:(BOOL)animated {	
	[super viewDidAppear:animated];
	
	NSLog(@"TopicViewController - viewDidAppear, topicId = %@", topicId);

}
*/

- (void)viewWillAppear:(BOOL)animated {

	NSLog(@"TopicViewController - viewWillAppear, topicId = %@, parentId = %@", topicId, parentId);

	[self reloadData];
}

- (void)reloadData {
	
	NSString *urlstr = [NSString stringWithFormat:@"%@/wap?%@", URLRoot, topicId];
	
	NSDictionary *map = [[[[[HttpMethod alloc] autorelease] doGet:urlstr] JSONValue] retain];
	topicData = [[map objectForKey:@"data"] retain];
	NSLog(@"topicData = %@", topicData);
	[map release];
	
	[self.tableView reloadData];
}

- (IBAction)clickButton:(id)sender {

	PostViewController *postView = [[PostViewController alloc] initWithNibName:@"PostViewController" bundle:nil];
	postView.title = self.title;
	postView.topicId = self.topicId;
	[super.navigationController pushViewController:postView animated:YES];
	[postView release];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark Table view data source


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
	
    return 2;
}

/*
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger) section {
	
	 switch (section) {
		 case 0:return @"書き込み";
		 case 1:return @"コメント";
	 default:
			 return nil;
	 }

}
*/

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	switch (section) {
		case 0:return 2;
		case 1:return [topicData count] - 1;
		default:
			return 0;
	}
}

- (IBAction)deleteTopic:(id)sender {

	NSLog(@"deleteTopic:%@", self.topicId);
	
	btnTarget = BTN_TOPIC;
	UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"本当に削除しますか？"
										message:@"書き込みも消えますので\r\nご注意ください。"
										delegate:self
										cancelButtonTitle:@"OK" otherButtonTitles:@"Cencel",nil];
	[alert show];
	[alert release];
}

- (IBAction)editTopic:(id)sender {
	
	btnTarget = BTN_TOPIC;
	NSLog(@"editTopic:%@", self.topicId);
}


- (IBAction)deleteComment:(id)sender {
	
	UIButton *btn = (UIButton*)sender;
	
	NSString* url = [[topicData objectAtIndex:btn.tag] objectAtIndex:C_url];
	NSLog(@"deleteComment:%@", url);
	self.parentId = url;
	btnTarget = BTN_COMMENT;

	UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"確認"
										message:@"書き込みを削除しますか？"
										delegate:self
										cancelButtonTitle:@"OK" otherButtonTitles:@"Cencel",nil];
	[alert show];
	[alert release];
}

- (void)alertView:(UIAlertView*) alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	
	NSString *btnName = @"";
	switch (buttonIndex) {
		case 0:	//OK
			btnName = @"OK";
			
			if (btnTarget == BTN_TOPIC) {
			
				//delete action
				NSMutableDictionary* param = [NSMutableDictionary dictionary];
					[param setObject:@"delete_topic" forKey:@"a"];
					[param setObject:self.topicId forKey:@"topic_id"];
					[param setObject:[self.parentId stringByReplacingOccurrencesOfString:@"&" withString:@"+"] forKey:@"parent_id"];
				[[[HttpMethod alloc] autorelease] doPost:@"/post" parameters:param];

				//reload parent screen then go back
				NSArray *allConts = self.navigationController.viewControllers;
				UITableViewController *parent = [allConts objectAtIndex:[allConts count] - 2];
				[parent.tableView reloadData];
				[self.navigationController popViewControllerAnimated:YES];

			}else if (btnTarget == BTN_COMMENT) {
				
				NSMutableDictionary* param = [NSMutableDictionary dictionary];
				[param setObject:@"delete_comment" forKey:@"a"];
				//#### Note parent_id and topic_id are switched
				[param setObject:self.parentId forKey:@"topic_id"];
				[param setObject:[self.topicId stringByReplacingOccurrencesOfString:@"&" withString:@"+"] forKey:@"parent_id"];
				[[[HttpMethod alloc] autorelease] doPost:@"/post" parameters:param];

				[self reloadData];
			}


			break;
		case 1:	//Cancel
			btnName = @"Cancel";
			break;
		default:
			break;
	}
	NSLog(@"deleteTopic:%@", btnName);
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
    //static NSString *CellIdentifier = @"Cell";
	NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d-%d", indexPath.section, indexPath.row];
	
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        //cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
		
		if (indexPath.section == 0 && indexPath.row == 0){
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
		}else{
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		}
	}

	NSLog(@"in section %d row %d", indexPath.section, indexPath.row);
	//NSString *val = nil;
	
	cell.textLabel.font = [UIFont systemFontOfSize:14.0];
	cell.detailTextLabel.textColor = [UIColor blackColor];
	NSString *bodyHtml = @"<body style=\"background-color:transparent;margin:0px;font-size:10pt;\">";

	if (indexPath.section == 0) {
		if(indexPath.row == 0){
			cell.textLabel.text = [NSString stringWithFormat:@"%@  %@",
							[[topicData objectAtIndex:0] objectAtIndex:C_date],
							[[topicData objectAtIndex:0] objectAtIndex:C_author]];

			cell.detailTextLabel.text = [[topicData objectAtIndex:0] objectAtIndex:C_title];
			cell.detailTextLabel.textColor = [UIColor blueColor];

			UIButton *btnDel = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
				btnDel.frame = CGRectMake(250, 1, 45, 20);
				[btnDel setTitle:@"削除" forState:UIControlStateNormal];
				[btnDel addTarget:self action:@selector(deleteTopic:)forControlEvents:UIControlEventTouchDown];
				btnDel.hidden = YES;
				[cell.contentView addSubview:btnDel];
			[btnDel release];

			UIButton *btnEdit = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
				btnEdit.frame = CGRectMake(200, 1, 45, 20);
				[btnEdit setTitle:@"編集" forState:UIControlStateNormal];
				[btnEdit addTarget:self action:@selector(editTopic:)forControlEvents:UIControlEventTouchDown];
				btnEdit.hidden = YES;
				[cell.contentView addSubview:btnEdit];
			[btnEdit release];
		}else if (indexPath.row == 1) {
			//cell.textLabel.text = @"";
			//cell.detailTextLabel.text = [[topicData objectAtIndex:0] objectAtIndex:3];
			
			UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(12.0f, 0.0f, 298.0f, 198.0f)];
			//webView.scalesPageToFit = YES;
			webView.userInteractionEnabled = FALSE;
			[[webView.subviews objectAtIndex:0] setScrollEnabled:FALSE];
			[[webView.subviews objectAtIndex:0] setBounces:FALSE];
			[webView setBackgroundColor:[UIColor clearColor]];
			[webView setOpaque:NO];

			NSArray *imgArr = [[topicData objectAtIndex:0] objectAtIndex:C_images];
			NSString *imgUrl = @"";
			int imgSize = 120;
			if ([imgArr count] > 0) {
				if ([imgArr count] > 2) {
					imgSize = 90;
				}
				
				for (int i = 0; i < [imgArr count]; i++) {
					imgUrl = [NSString stringWithFormat:@"%@<img src='%@' width='%dpx'/>&nbsp;",
							  imgUrl, [imgArr objectAtIndex:i], imgSize];
				}
				imgUrl = [NSString stringWithFormat:@"%@<br/>", imgUrl];
			}

			[webView loadHTMLString:[NSString stringWithFormat:@"%@%@%@</body>",
							bodyHtml, imgUrl, [[topicData objectAtIndex:0] objectAtIndex:C_body]]
							baseURL:nil];
			[cell addSubview:webView];
			[webView release];
		}

	}else{
		if ([topicData count] > 1) {

			UIWebView *webView = [[[UIWebView alloc]initWithFrame:CGRectMake(12.0f, 2.0f, 298.0f, 204.0f)] retain];
			//webView.scalesPageToFit = YES;
			webView.userInteractionEnabled = FALSE;
			[[webView.subviews objectAtIndex:0] setScrollEnabled:FALSE];
			[[webView.subviews objectAtIndex:0] setBounces:FALSE];
			[webView setBackgroundColor:[UIColor clearColor]];
			[webView setOpaque:NO];
			
			NSArray *imgArr = [[topicData objectAtIndex:indexPath.row+1] objectAtIndex:C_images];
			NSString *imgUrl = @"";
			int imgSize = 120;
			if ([imgArr count] > 0) {
				if ([imgArr count] > 2) {
					imgSize = 90;
				}

				for (int i = 0; i < [imgArr count]; i++) {
					imgUrl = [NSString stringWithFormat:@"%@<img src='%@' width='%dpx'/>&nbsp;&nbsp;",
								imgUrl, [imgArr objectAtIndex:i], imgSize];
				}
				imgUrl = [NSString stringWithFormat:@"%@<br/>", imgUrl];
			}

			[webView loadHTMLString:
				[NSString stringWithFormat:@"%@%@ &nbsp; %@<br/>%@%@</body>", bodyHtml,
									 [[topicData objectAtIndex:indexPath.row+1] objectAtIndex:C_date],
									 [[topicData objectAtIndex:indexPath.row+1] objectAtIndex:C_title],imgUrl,
									 [[topicData objectAtIndex:indexPath.row+1] objectAtIndex:C_body]]
							baseURL:nil];
			[cell addSubview:webView];
			[webView release];

			//Comment delete button
			if ([(NSString*)[[topicData objectAtIndex:indexPath.row+1] objectAtIndex:C_url] isEqualToString:@"N/A"] == NO) {

				UIButton *btnDel = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
				btnDel.tag = (int)indexPath.row+1;
				btnDel.frame = CGRectMake(250, 1, 45, 20);
				[btnDel setTitle:@"削除" forState:UIControlStateNormal];
				[btnDel addTarget:self action:@selector(deleteComment:)forControlEvents:UIControlEventTouchDown];
				[cell.contentView addSubview:btnDel];
				[btnDel release];
			}
		}
	}

	// Set up the cell...
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	if (indexPath.section == 0) {
		if(indexPath.row == 1) {
			return 210; // 一番上のセクションの一番上の行の高さは80ピクセルにします。
		}
	} else if (indexPath.section == 1) {
		return 210; // 二番目のセクションの行の高さは全て60ピクセルにします。 
	}
	return 60; // 上で指定しなかった全てのセクション・行の高さは全て45ピクセルにします。
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

}


- (void)dealloc {
    [super dealloc];
	[topicData release];
}


@end
